﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Simple.Services.System.QHSEViolationCategory.Models;
using System.Xml;
using Simple.Services.System.QHSEUser.Models;

namespace Simple.Services;

public class QHSEOverLappingOrganizationService
{
    private readonly SimpleDbContext _context;
    public QHSEOverLappingOrganizationService(SimpleDbContext context)
    {
        _context = context;
    }
    public async Task<List<QHSEOverLappingOrganizationModel>> GetAsync()
    {
        var organizations = await _context.Set<QHSESysOverLappingOrganization>().AsNoTracking().Where(u => u.RowState == 0).ToListAsync();

        return MapperHelper.Map<List<QHSEOverLappingOrganizationModel>>(organizations);
    }

    public async Task<PageResultModel<QHSEOverLappingOrganizationModel>> GetPageAsync(QHSEOverLappingOrganizationPageInputModel input)
    {
        var result = new PageResultModel<QHSEOverLappingOrganizationModel>();
        var query = _context.Set<QHSESysOverLappingOrganization>().AsNoTracking().Where(u => u.RowState == 0 && u.OrganizationId != "11").AsQueryable();

        if (!string.IsNullOrEmpty(input.ParentId) && input.ParentId != "11")
        {
            query = query.Where(u => EF.Functions.Like(u.IdPath, $"%{input.ParentId}%"));
        }
        if (!string.IsNullOrEmpty(input.OrganizationName))
        {
            query = query.Where(u => EF.Functions.Like(u.OrganizationName, $"%{input.OrganizationName}%"));
        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.DataSort).Page(input.PageNo, input.PageSize);
        var organizations = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEOverLappingOrganizationModel>>(organizations);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    public async Task<QHSEOverLappingOrganizationModel> GetByIdAsync(IdInputModel idInput)
    {
        var violationCategory = await _context.Set<QHSESysOverLappingOrganization>().FindAsync(idInput.Id);
        if (violationCategory == null)
        {
            return null;
        }
        else
        {
            return MapperHelper.Map<QHSEOverLappingOrganizationModel>(violationCategory);
        }
    }
    public async Task<List<QHSEOverLappingOrganizationTreeNodeModel>> GetAsync(QHSEOverLappingOrganizationInputModel input)
    {
        var query = _context.Set<QHSESysOverLappingOrganization>().AsNoTracking().Where(u => u.RowState == 0 && u.OrganizationId != "11").AsQueryable();

        // 根据条件查询
        if (!string.IsNullOrEmpty(input.Name))
        {
            query = query.Where(m => EF.Functions.Like(m.OrganizationName, $"%{input.Name}%"));
        }

        // 排序
        query = query.OrderBy(m => m.DataSort);

        var organizations = await query.ToListAsync();
        var nodes = MapperHelper.Map<List<QHSEOverLappingOrganizationTreeNodeModel>>(organizations);

        var builder = QHSEOverLappingOrganizationTreeNodeModel.CreateBuilder(nodes, "11");
        return builder.Build();
    }
    public async Task<int> AddAsync(QHSEOverLappingOrganizationModel model)
    {
        Guid guid = Guid.NewGuid();
        string guidString = RemoveHyphens(guid);
        if (string.IsNullOrEmpty(model.OrganizationId))
        {
            model.OrganizationId = guidString;
        }
        if (string.IsNullOrEmpty(model.IdPath) || string.IsNullOrEmpty(model.NamePath))
        {
            IdInputModel modelInput = new IdInputModel();
            modelInput.Id = model.ParentId;
            var parent = await GetByIdAsync(modelInput);
            if (model.ParentId != "11")
            { 
                model.IdPath = parent.IdPath + "_" + model.OrganizationId;
                model.NamePath = parent.NamePath + "_" + model.OrganizationName;
            }
            else
            {
                model.IdPath = model.OrganizationId;
                model.NamePath =model.OrganizationName;
            }
            
        }
        var organization = MapperHelper.Map<QHSESysOverLappingOrganization>(model);
        await _context.AddAsync(organization);
        return await _context.SaveChangesAsync();
    }
    public async Task<int> EditAsync(QHSEOverLappingOrganizationModel model)
    {
        IdInputModel modelInput = new IdInputModel();
        modelInput.Id = model.ParentId;
        var parent = await GetByIdAsync(modelInput);
        if (model.ParentId != "11")
        {
            model.IdPath = parent.IdPath + "_" + model.OrganizationId;
            model.NamePath = parent.NamePath + "_" + model.OrganizationName;
        }
        else
        {
            model.IdPath = model.OrganizationId;
            model.NamePath = model.OrganizationName;
        }
        var organization = MapperHelper.Map<QHSESysOverLappingOrganization>(model);
        _context.Update(organization);
        return await _context.SaveChangesAsync();
    }
    static string RemoveHyphens(Guid guid)
    {
        return guid.ToString().Replace("-", ""); // 通过 Replace 函数移除连字符 "-"
    }
    public async Task<List<AntTreeNode>> GetTreeAsync()
    {
        var organizations = await _context.Set<QHSESysOverLappingOrganization>().AsNoTracking().Where(u=>u.RowState == 0 && u.OrganizationId != "11").OrderBy(u => u.DataSort).ThenBy(u=>u.OrganizationName).AsNoTracking().ToListAsync();
        List<TreeNode> nodes = MapperHelper.Map<List<TreeNode>>(organizations);

        var builder = AntTreeNode.CreateBuilder(nodes, "11");
        return builder.Build();
    }
    public async Task<List<AntTreeNode>> GetTreeAsync(IdInputModel idInputModel)
    {
        var organizations = await _context.Set<QHSESysOverLappingOrganization>().AsNoTracking().Where(u => u.RowState == 0 && u.OrganizationId != "11").Where(u=>u.NamePath.Contains(idInputModel.Id)).OrderBy(u=> u.DataSort).ThenBy(u => u.OrganizationName).AsNoTracking().ToListAsync();
        List<TreeNode> nodes = MapperHelper.Map<List<TreeNode>>(organizations);

        var builder = AntTreeNode.CreateBuilder(nodes, "11");
        return builder.Build();
    }

    public async Task<int> DeleteAsync(IEnumerable<string> ids)
    {
        var organizations = await _context.Set<QHSESysOverLappingOrganization>()
            .Where(a => ids.Contains(a.OrganizationId))
            .ToListAsync();
        foreach (var organization in organizations)
        {
            organization.RowState = -1;
        }
        _context.UpdateRange(organizations);
        int ret = await _context.SaveChangesAsync();
        return ret;
    }
}
